package com.ruoyi.dataAnalysis.controller;


import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.dataAnalysis.domain.*;

import com.ruoyi.dataAnalysis.service.DataAnalysisService;
import com.ruoyi.permission.Dao.SerDevicePermi;
import com.ruoyi.permission.domain.DeviceIdAndInsectRet;
import com.ruoyi.permission.domain.DevicePermiInsectInfo;
import com.ruoyi.permission.mapper.SerDevicePermiMapper;
import com.ruoyi.permission.mapper.SerUnitUserMapper;
import com.ruoyi.utils.MyDateUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.annotation.Id;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Field;
import java.util.*;

/**
 * @author LiSuxuan
 * @date 2021年 04月 27日 11:10
 */
@Api("dataAnalysis")
@Slf4j
@RestController
@RequestMapping("/data")
public class DataAnalysisController {

    @Autowired
    private DataAnalysisService dataAnalysisService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private SerDevicePermiMapper permiMapper;
    @Autowired
    private SerUnitUserMapper unitUserMapper;

    /**
     * 时间段内虫子发生总
     * @param deviceIds
     * @param dataResponse
     * @return
     */
    @ApiOperation("时间段内虫子发生总量，接口参数起止时间，例如：http://localhost:8184/data/total?params%5BbeginTime%5D=2021-04-07&params%5BendTime%5D=2021-04-07")
    @GetMapping("/totalByDevice")
    public AjaxResult insectTotalByDeviceId(String deviceIds,DataResponse dataResponse) {
        Long userIdL = SecurityUtils.getLoginUser().getUser().getUserId();
        Integer userId= userIdL.intValue();
        Integer unitId = 0;
        if(userId != 1 && userId != 20 && userId != 37) {
            unitId = unitUserMapper.selectByPrimaryKey(userId).getUnitId();
        }
        //按设备号查找昆虫总数 tag_manual的list表
        List<String> list = dataAnalysisService.selectInsectTotalListByDeviceIds(dataResponse,deviceIds);
//        log.info("111"+ list.toString());
        DataAnalysisController dataAnalysisController = new DataAnalysisController();
        InsectType insectType = dataAnalysisController.json2InsectType(list);
        log.info("insectTYpe:"+insectType);
        HashMap<String,Integer> insectTypeMap = new HashMap<>();
        if(unitId !=0) {
            //获取虫情权限
            String[] item = deviceIds.split(",");
            List<String> deviceIdList = new ArrayList<>(Arrays.asList(item));
            List<Integer> idList = new ArrayList<>();
            List<SerDevicePermi> serDevicePermiList = permiMapper.selectAllId();
            for(SerDevicePermi serDevicePermi:serDevicePermiList) {
                for (String deviceId : deviceIdList) {
                    if(Integer.valueOf(deviceId) == serDevicePermi.getDeviceNo()) {
                        idList.add(serDevicePermi.getId());
                    }
                }
            }
            List<DevicePermiInsectInfo> insectPermiLst = new ArrayList<>();
//            for(String deviceId :deviceIdList){
//                List<DevicePermiInsectInfo> devicePermiInsectInfos = permiMapper.selectInsectListByDeviceId(Integer.parseInt(deviceId));
//                insectPermiLst.addAll(devicePermiInsectInfos);
//            }
            List<DevicePermiInsectInfo> devicePermiInsectInfoLst = permiMapper.selectAllInsectList();
            for (Integer id : idList) {
                for (DevicePermiInsectInfo devicePermiInsectInfo : devicePermiInsectInfoLst) {
                    if (devicePermiInsectInfo.getDeviceId() == id) {
                        insectPermiLst.add(devicePermiInsectInfo);
                    }
                }
            }

            for (DevicePermiInsectInfo insectPermi : insectPermiLst) {
                String ret = insectPermi.getRet();
                try{
                    Field field = InsectType.class.getDeclaredField(ret);
                    field.setAccessible(true);
                    Integer value = field.getInt(insectType);
                    insectTypeMap.put(ret,value);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return AjaxResult.success(insectTypeMap);
        }else{
            Field[] fields = InsectType.class.getDeclaredFields();
            for(Field field:fields){
                try{
                    field.setAccessible(true);
                    Integer value = field.getInt(insectType);
                    insectTypeMap.put(field.getName(),value);
                } catch (IllegalAccessException e) {
                    throw new RuntimeException(e);
                }
            }
        }
        return AjaxResult.success(insectTypeMap);
    }


    /**
     * 每台设备 不同时间的发生量, 根据起止时间计算阶段时间内 每天虫子的数量
     *
     * @param startTime 开始时间 示例：2021-05-03
     * @param endTime   结束时间
     * @return 查询列表
     */
    @ApiOperation("不同时间发生量，startTime 开始时间 示例:http://localhost:8184/data/difTime?startTime=2021-04-04&endTime=2021-04-07")
    @GetMapping("/difTimeByDevice")
    public AjaxResult insectDiffTimeByDeviceId(String deviceIds,String startTime, String endTime) {
        Long userIdL = SecurityUtils.getLoginUser().getUser().getUserId();
        Integer userId= userIdL.intValue();
        Integer unitId = 0;
        if(userId != 1 && userId != 20 && userId != 37) {
            unitId = unitUserMapper.selectByPrimaryKey(userId).getUnitId();
        }
        /* 计算时间间隔，按 天 存入 集合 */
        List<String> dates = MyDateUtil.calculateTimeInterval(startTime, endTime);
        if (dates == null) {
            return AjaxResult.error("输入日期有误!");
        }

        /* 存放结果数据集 */
        List<InsectStatistic> statistics = new ArrayList<>();
        DataAnalysisController dataAnalysisController = new DataAnalysisController();
        InsectStatistic totoal_by_class = new InsectStatistic();
        totoal_by_class.setDay("ALL_DAY:CLASS_BY_SUM");
        totoal_by_class.setInsectType(new InsectType(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0));
        int totalSum = 0;
        HashMap<String,Integer> insectTypeMapTotal = new HashMap<>();
        DataResponse dataResponse = new DataResponse();
        dataResponse.setBeginTime(startTime).setEndTime(endTime);
        List<PhotoTimeAndTagManual> photoTimeAndTagManualLst = dataAnalysisService.selectInsectByDeviceIds(deviceIds, dataResponse);
//        InsectType insectType = dataAnalysisController.json2InsectType(tagManualList);

        for(String date : dates){
            List<String> list = new ArrayList<>();
            for(PhotoTimeAndTagManual photoTimeAndTagManual:photoTimeAndTagManualLst) {
                if (photoTimeAndTagManual.getPhotoTime().substring(0, 10).equals(date)) {
                    list.add(photoTimeAndTagManual.getTagManual());
                }
            }
            InsectType insectType = dataAnalysisController.json2InsectType(list);
            //        存储权限虫子
            HashMap<String,Integer> insectTypeMap = new HashMap<>();
            if (unitId != 0) {
                //获取虫情权限
                String[] item = deviceIds.split(",");
                List<String> deviceIdList = new ArrayList<>(Arrays.asList(item));

                List<Integer> idList = new ArrayList<>();
                List<SerDevicePermi> serDevicePermiList = permiMapper.selectAllId();
                for(SerDevicePermi serDevicePermi:serDevicePermiList) {
                    for (String deviceId : deviceIdList) {
                        if(Integer.valueOf(deviceId) == serDevicePermi.getDeviceNo()) {
                            idList.add(serDevicePermi.getId());
                        }
                    }
                }

                List<DevicePermiInsectInfo> insectPermiLst = new ArrayList<>();
                List<DevicePermiInsectInfo> devicePermiInsectInfoLst = permiMapper.selectAllInsectList();
                for (Integer id : idList) {
                    for (DevicePermiInsectInfo devicePermiInsectInfo : devicePermiInsectInfoLst) {
                        if (devicePermiInsectInfo.getDeviceId() == id) {
                            insectPermiLst.add(devicePermiInsectInfo);
                        }
                    }
                }
                for (DevicePermiInsectInfo insectPermi : insectPermiLst) {
                    String ret = insectPermi.getRet();
                    try {
                        Field field = InsectType.class.getDeclaredField(ret);
                        field.setAccessible(true);
                        Integer value = field.getInt(insectType);
                        insectTypeMap.put(ret, value);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            } else {
                Field[] fields = InsectType.class.getDeclaredFields();
                for (Field field : fields) {
                    try {
                        field.setAccessible(true);
                        Integer value = field.getInt(insectType);
                        insectTypeMap.put(field.getName(), value);
                    } catch (IllegalAccessException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
            log.info(insectTypeMap.toString());
        //如果不为管理员
//        for (String date : dates) {
//            DataResponse dataResponse = new DataResponse();
//            dataResponse.setDate(date);
//            List<String> list = dataAnalysisService.selectInsectByDeviceId(deviceIds,dataResponse);
//            InsectType insectType = dataAnalysisController.json2InsectType(list);
//            //存储权限虫子
//            HashMap<String,Integer> insectTypeMap = new HashMap<>();
//            //如果不为管理员
//            if(unitId!=0) {
//                //获取虫情权限
//                String[] item = deviceIds.split(",");
//                List<String> deviceIdList = new ArrayList<>(Arrays.asList(item));
//                List<DevicePermiInsectInfo> insectPermiLst = new ArrayList<>();
//                for(String deviceId :deviceIdList){
//                    List<DevicePermiInsectInfo> devicePermiInsectInfos = permiMapper.selectInsectListByDeviceId(Integer.parseInt(deviceId));
//                    insectPermiLst.addAll(devicePermiInsectInfos);
//                }
//
//                for(DevicePermiInsectInfo insectPermi:insectPermiLst){
//                    String ret = insectPermi.getRet();
//                    try{
//                        Field field = InsectType.class.getDeclaredField(ret);
//                        field.setAccessible(true);
//                        Integer value = field.getInt(insectType);
//                        insectTypeMap.put(ret,value);
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                    }
//                }
//            }else{
//                Field[] fields = InsectType.class.getDeclaredFields();
//                for(Field field:fields){
//                    try{
//                        field.setAccessible(true);
//                        Integer value = field.getInt(insectType);
//                        insectTypeMap.put(field.getName(),value);
//                    } catch (IllegalAccessException e) {
//                        throw new RuntimeException(e);
//                    }
//                }
//            }
//            log.info(insectTypeMap.toString());

            InsectStatistic insectStatistic = new InsectStatistic();
            insectStatistic.setInsectType(insectTypeMap);
            insectStatistic.setDay(date);
            int sumByDay = 0;
            for(Map.Entry<String,Integer> entry: insectTypeMap.entrySet()){
                String insectTag = entry.getKey();
                int tagCount = entry.getValue();
                sumByDay += tagCount;
                // total 计算每一类的和
                Integer currentTag = insectTypeMapTotal.get(insectTag);
                if(currentTag ==null){
                    insectTypeMapTotal.put(insectTag,tagCount);
                }else {
                    insectTypeMapTotal.put(insectTag, tagCount + currentTag);
                }
                totoal_by_class.setInsectType(insectTypeMapTotal);
            }
            totalSum += sumByDay;
            insectStatistic.setSum(sumByDay);
            statistics.add(insectStatistic);
        }
        totoal_by_class.setSum(totalSum);
        statistics.add(totoal_by_class);
        return AjaxResult.success(statistics);
    }


    /**
     * 根据设备导出数据
     * @param deviceIds
     * @param startTime
     * @param endTime
     * @param response
     * @return
     */
    @GetMapping("/downloadStatisticDataByDevice")
    public AjaxResult download_statistic_data_by_deviceId(String deviceIds,String startTime, String endTime, HttpServletResponse response){
        Long userIdL = SecurityUtils.getLoginUser().getUser().getUserId();
        Integer userId= userIdL.intValue();
        Integer unitId = 0;
        if(userId != 1 && userId != 20 && userId != 37) {
            unitId = unitUserMapper.selectByPrimaryKey(userId).getUnitId();
        }
        /* 计算时间间隔，按 天 存入 集合 */
        List<String> dates = MyDateUtil.calculateTimeInterval(startTime, endTime);
        if (dates == null) {
            return AjaxResult.error("输入日期有误!");
        }
        /* 存放结果数据集 */
        List<InsectStatistic> statistics = new ArrayList<>();
        DataAnalysisController dataAnalysisController = new DataAnalysisController();
        for (String date : dates) {
            DataResponse dataResponse = new DataResponse();
            dataResponse.setDate(date);
            List<String> list = dataAnalysisService.selectInsectByDeviceId(deviceIds,dataResponse);
            InsectType insectType = dataAnalysisController.json2InsectType(list);
            InsectStatistic insectStatistic = new InsectStatistic();
            //存储用户虫情权限列表
            HashMap<String,Integer> insectTypeMap = new HashMap<>();
            //如果不为管理员
            if(unitId!=0) {
                //获取虫情权限
                String[] item = deviceIds.split(",");
                List<String> deviceIdList = new ArrayList<>(Arrays.asList(item));
                List<DevicePermiInsectInfo> insectPermiLst = new ArrayList<>();
                for(String deviceId :deviceIdList){
                    List<DevicePermiInsectInfo> devicePermiInsectInfos = permiMapper.selectInsectListByDeviceId(Integer.parseInt(deviceId));
                    insectPermiLst.addAll(devicePermiInsectInfos);
                }
                for(DevicePermiInsectInfo insectPermi:insectPermiLst){
                    String ret = insectPermi.getRet();
                    try{
                        Field field = InsectType.class.getDeclaredField(ret);
                        field.setAccessible(true);
                        Integer value = field.getInt(insectType);
                        insectTypeMap.put(ret,value);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }else{
                Field[] fields = InsectType.class.getDeclaredFields();
                for(Field field:fields){
                    try{
                        field.setAccessible(true);
                        Integer value = field.getInt(insectType);
                        insectTypeMap.put(field.getName(),value);
                    } catch (IllegalAccessException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
            insectStatistic.setInsectType(insectTypeMap);
            insectStatistic.setDay(date);
            //用于统计每天的虫子总数
            int sumByDay = 0;
            for(Map.Entry<String,Integer> entry: insectTypeMap.entrySet()) {
                int tagCount = entry.getValue();
                sumByDay += tagCount;
            }
            insectStatistic.setSum(sumByDay);
            statistics.add(insectStatistic);
        }
        log.info("statistics =" + statistics);
        List<ExportStatisticData> res_lst = new ArrayList<>();
        for(InsectStatistic data: statistics){
            ExportStatisticData ins_data = new ExportStatisticData();
            ins_data.setAllInsectNum(data.getInsectType(), data.getDay());
            res_lst.add(ins_data);
        }
        ExcelUtil<ExportStatisticData> util = new ExcelUtil<>(ExportStatisticData.class);
        AjaxResult excelresult = new AjaxResult();
        String name = "虫情数据分析导出表";
        excelresult = util.exportExcel(res_lst, name);
        String fileName = (String) excelresult.get("msg");
        try
        {
            if (!FileUtils.checkAllowDownload(fileName))
            {
                throw new Exception(StringUtils.format("文件名称({})非法，不允许下载。 ", fileName));
            }
            String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
            String filePath = RuoYiConfig.getDownloadPath() + fileName;

            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, realFileName);
            FileUtils.writeBytes(filePath, response.getOutputStream());
            if (true)
            {
                FileUtils.deleteFile(filePath);
            }
        }
        catch (Exception e)
        {
            return AjaxResult.error("下载文件失败", e);
        }
        return AjaxResult.success("下载文件成功！");

    }

    /**
     * 将数据库中的JSON格式转换为对象格式
     *
     * @param list list列表
     * @return InsectType类型
     */
    public InsectType json2InsectType(List<String> list) {

//        int z0 = 0;
//        int z1 = 0;
//        int other = 0;
//
//        int z2 = 0;
//        int z3 = 0;
//        int z4 = 0;
//        int z5 = 0;
//        int z6 = 0;
//        int z7 = 0;
//        int z8 = 0;
//        int z9 = 0;
//        int z10 = 0;
//        int z11 = 0;
//        int z12 = 0;
//        int z13 = 0;
//        int z14 = 0;
        int y1 = 0;
        int y2 = 0;
        int y3 = 0;
        int y4 = 0;
        int y5 = 0;
        int y6 = 0;
        int y7 = 0;
        int y8 = 0;
        int y9 = 0;

        int e1 = 0;
        int e2 = 0;
        int e3 = 0;
        int e4 = 0;
        int e5 = 0;
        int e6 = 0;
        int e7 = 0;
        int e8 = 0;
        int e9 = 0;
        int e10 = 0;
        int e11 = 0;
        int e12 = 0;

        int q1 = 0;
        int q2 = 0;
        int q3 = 0;
        int q4 = 0;
        int q5 = 0;
        int q6 = 0;
        int q7 = 0;
        int q8 = 0;
        int q9 = 0;
        int q10 = 0;
        int q11 = 0;
        int q12 = 0;
        int q13 = 0;
        int q14 = 0;
        int q15 = 0;
        int q16 = 0;
        int q17 = 0;
        int q18 = 0;
        int x1 = 0;
        int x2 = 0;
        int x3 = 0;
        int e120 = 0;
        int e90 = 0;
        int e40 = 0;
        int a41 = 0;
        int a10 = 0;


        for (String s : list) {
            if (s != null) {
                InsectType totalNum = JSON.parseObject(s, InsectType.class);
                if(totalNum != null) {
                    if (totalNum.get("y1") != null) y1 += totalNum.get("y1");
                    if (totalNum.get("y2") != null) y2 += totalNum.get("y2");
                    if (totalNum.get("y3") != null) y3 += totalNum.get("y3");
                    if (totalNum.get("y4") != null) y4 += totalNum.get("y4");
                    if (totalNum.get("y5") != null) y5 += totalNum.get("y5");
                    if (totalNum.get("y6") != null) y6 += totalNum.get("y6");
                    if (totalNum.get("y7") != null) y7 += totalNum.get("y7");
                    if (totalNum.get("y8") != null) y8 += totalNum.get("y8");
                    if (totalNum.get("y9") != null) y9 += totalNum.get("y9");

                    if (totalNum.get("e1") != null) e1 += totalNum.get("e1");
                    if (totalNum.get("e2") != null) e2 += totalNum.get("e2");
                    if (totalNum.get("e3") != null) e3 += totalNum.get("e3");
                    if (totalNum.get("e4") != null) e4 += totalNum.get("e4");
                    if (totalNum.get("e5") != null) e5 += totalNum.get("e5");
                    if (totalNum.get("e6") != null) e6 += totalNum.get("e6");
                    if (totalNum.get("e7") != null) e7 += totalNum.get("e7");
                    if (totalNum.get("e8") != null) e8 += totalNum.get("e8");
                    if (totalNum.get("e9") != null) e9 += totalNum.get("e9");
                    if (totalNum.get("e10") != null) e10 += totalNum.get("e10");
                    if (totalNum.get("e11") != null) e11 += totalNum.get("e11");
                    if (totalNum.get("e12") != null) e12 += totalNum.get("e12");

                    if (totalNum.get("q1") != null) q1 += totalNum.get("q1");
                    if (totalNum.get("q2") != null) q2 += totalNum.get("q2");
                    if (totalNum.get("q3") != null) q3 += totalNum.get("q3");
                    if (totalNum.get("q4") != null) q4 += totalNum.get("q4");
                    if (totalNum.get("q5") != null) q5 += totalNum.get("q5");
                    if (totalNum.get("q6") != null) q6 += totalNum.get("q6");
                    if (totalNum.get("q7") != null) q7 += totalNum.get("q7");
                    if (totalNum.get("q8") != null) q8 += totalNum.get("q8");
                    if (totalNum.get("q9") != null) q9 += totalNum.get("q9");
                    if (totalNum.get("q10") != null) q10 += totalNum.get("q10");
                    if (totalNum.get("q11") != null) q11 += totalNum.get("q11");
                    if (totalNum.get("q12") != null) q12 += totalNum.get("q12");
                    if (totalNum.get("q13") != null) q13 += totalNum.get("q13");
                    if (totalNum.get("q14") != null) q14 += totalNum.get("q14");
                    if (totalNum.get("q15") != null) q15 += totalNum.get("q15");
                    if (totalNum.get("q16") != null) q16 += totalNum.get("q16");
                    if (totalNum.get("q17") != null) q17 += totalNum.get("q17");
                    if (totalNum.get("q18") != null) q18 += totalNum.get("q18");
                    if (totalNum.get("x1") != null) x1 += totalNum.get("x1");
                    if (totalNum.get("x2") != null) x2 += totalNum.get("x2");
                    if (totalNum.get("x3") != null) x3 += totalNum.get("x3");
                    if (totalNum.get("e120") != null) e120 += totalNum.get("e120");
                    if (totalNum.get("e90") != null) e90 += totalNum.get("e90");
                    if (totalNum.get("e40") != null) e40 += totalNum.get("e40");
                    if (totalNum.get("a41") != null) a41 += totalNum.get("a41");
                    if (totalNum.get("a10") != null) a10 += totalNum.get("a10");
                }
            }
        }
//        log.info("y1=" + y1);
//        log.info("y2=" + y2);
//        log.info("test"+ new InsectType(y1, y2, y3, y4, y5, y6, y7, y8, y9,
//                e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12,
//                q1, q2, q3, q4, q5, q6, q7, q8, q9, q10, q11, q12, q13, q14, q15, q16, q17, q18,
//                x1, x2, x3, e120, e90, e40, a41,a10));
        InsectType insectType = new InsectType(y1, y2, y3, y4, y5, y6, y7, y8, y9,
                e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12,
                q1, q2, q3, q4, q5, q6, q7, q8, q9, q10, q11, q12, q13, q14, q15, q16, q17, q18,
                x1, x2, x3, e120, e90, e40, a41,a10);
        return insectType;

    }

}
